import numpy as np
import scipy as sp
import json
from sklearn import tree
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
 
 
file1 = "./train_release-fasd-real.json"
file2 = "./train_release-fasd-attack.json"
file3 = "./test_release-fasd-real.json"
file4 = "./test_release-fasd-attack.json"

# file = "./video.json"



x_train = []
x_test = []
y_train = []
y_test = []



with open(file1, 'r')as f:
    list = json.load(f)
    data1 = np.array(list)

with open(file2, 'r')as f:
    list = json.load(f)
    data2 = np.array(list)

with open(file3, 'r')as f:
    list = json.load(f)
    data3 = np.array(list)

with open(file4, 'r')as f:
    list = json.load(f)
    data4 = np.array(list)

# 训练集
for i in range(len(data1)):
    x_train.append(np.array([data1[i]]))
    y_train.append(0)
    
for i in range(len(data2)):
    x_train.append(np.array([data2[i]]))
    y_train.append(1)

# 测试集
for i in range(len(data3)):
    x_test.append(np.array([data3[i]]))
    y_test.append(0)
    
for i in range(len(data4)):
    x_test.append(np.array([data4[i]]))
    y_test.append(1)

x_train = np.array((x_train))
x_test = np.array((x_test))
y_train = np.array((y_train))
y_test = np.array((y_test))

decision_tree_classifier = tree.DecisionTreeClassifier()
# parameters={'kernel':['linear','rbf','sigmoid','poly'],'C':np.linspace(0.1,20,50),'gamma':np.linspace(0.1,20,20)}
parameters = {'criterion':['entropy','gini'],'max_depth':[1,2,3,4,5]}

model = GridSearchCV(decision_tree_classifier,parameters)
model.fit(x_train,y_train)
model.best_params_
''' 使用信息熵作为划分标准，对决策树进行训练 '''
# clf = tree.DecisionTreeClassifier(criterion='entropy')
# print(clf)
# clf.fit(x_train, y_train)

# print("SVM-输出训练集的准确率为：",model.score(x_train,y_train))
print("输出训练集的准确率为")
y_hat = model.predict(x_train)
print(classification_report(y_train, y_hat, digits=4))
y_hat = model.predict(x_test)

# print("SVM-输出测试集的准确率为：",model.score(x_test,y_test))
print("输出测试集的准确率")
print(classification_report(y_test, y_hat, digits=4))
 
''' 把决策树结构写入文件 '''
# with open("tree.dot", 'w') as f:
#     f = tree.export_graphviz(model, out_file=f)
    
''' 系数反映每个特征的影响力。越大表示该特征在分类中起到的作用越大 '''
# print(model.feature_importances_)
 
